package com.zhxq.member.controller;

import com.zhxq.ai.domain.vo.MessageVo;
import com.zhxq.ai.repository.ChatHistoryRepository;
import com.zhxq.common.core.domain.AjaxResult;
import com.zhxq.member.socket.WebSocketKnowServer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/member/chat")
@Tag(name = "客户面试宝典会话管理")
@RequiredArgsConstructor
public class MemberKnowChatController {

    @Resource
    private ChatHistoryRepository mongoChatHistoryRepository;

    @Resource(name = "mongoChatMemoryConfig")
    private ChatMemory mongoChatMemory;

    private final WebSocketKnowServer webSocketKnowServer;

    /**
     * 根据用户和会话类型查询会话历史列表
     * @param chatType 业务类型，如：chat,service,pdf
     * @return chatId列表
     */
    @Operation(summary = "根据用户和会话类型查询会话历史列表")
    @GetMapping("/history/{chatType}")
    public AjaxResult getChatIds(@PathVariable("chatType") String chatType) {
        return AjaxResult.success(mongoChatHistoryRepository.getChatHistory(chatType));
    }

    /**
     * 根据chatId查询会话历史
     * @param type 业务类型，如：chat,service,pdf
     * @param chatId 会话id
     * @return 指定会话的历史消息
     */
    @Operation(summary = "根据chatId查询会话历史")
    @GetMapping("/message/{chatId}")
    public AjaxResult getChatHistory(@PathVariable("chatId") String chatId) {
        List<Message> messages = mongoChatMemory.get(chatId, Integer.MAX_VALUE);
        if(messages == null) {
            return AjaxResult.success(List.of());
        }
        return AjaxResult.success(messages.stream().map(MessageVo::new).toList());
    }

    /**
     * 知识库聊天
     * @param prompt
     * @param chatId
     * @return
     */
    @GetMapping
    @Operation(summary = "知识库聊天")
    public AjaxResult chat(String prompt, String chatId) throws InterruptedException {
        webSocketKnowServer.sendMessageToAI(prompt, chatId);
        return AjaxResult.success();
    }
}
